import { onMounted } from 'vue'
import { binarySearch } from './util'

export default function ({ menuRef, contentRef, anchorAttr = 'data-index' }) {
  const range = [-20, 20] // 计算正文滚动时最接近的菜单项
  let contentScrollTop = []

  function clickMenuItem(menuItem) {
    contentRef.value.scrollTo(menuItem.index)
  }

  // 正文滚动时触发，高亮对应的菜单项
  function scrollContent(scrollTop) {
    const arr = contentScrollTop
    const index = binarySearch(arr, (refer) => {
      if (scrollTop < refer.min) return 0
      else if (scrollTop > refer.max) return 2
      else return 1
    })
    index >= 0 && menuRef.value.select(arr[index].id)
  }

  // 计算正文区锚点距离顶部的高度
  function calcContentScrollTop() {
    const arr = []
    contentRef.value.wrapRef
      .querySelectorAll(`[${anchorAttr}]`)
      .forEach((el) => {
        arr.push({
          id: el.getAttribute(anchorAttr),
          top: el.offsetTop,
          min: el.offsetTop + range[0], // 提前计算，提高性能
          max: el.offsetTop + range[1],
        })
      })
    contentScrollTop = arr
  }

  onMounted(() => calcContentScrollTop())

  return {
    clickMenuItem,
    scrollContent,
    calcContentScrollTop,
  }
}
